package com.sumainfor.pc.market.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sumainfor.common.util.DateUtils;
import com.sumainfor.common.util.JsonResult;
import com.sumainfor.pc.market.dao.MarketDataMapper;
import com.sumainfor.pc.market.feign.BaseFeignZuul;
import com.sumainfor.pc.market.feign.TenantFeign;
import com.sumainfor.pc.market.util.FilterCenterUtil;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @Author PuaChen
 * @Create 2019-05-14 14:34
 */
@Service
@Transactional(rollbackFor = Exception.class)
@Log4j2
public class MarketDataService {

    @Autowired
    private MarketDataMapper mapper;

    @Autowired
    private BaseFeignZuul zuul;

    @Autowired
    private TenantFeign tenantFeign;


    /**
     * 查询主页表格数据
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param areaId    公司编号
     * @return
     */
    public JsonResult selectTableList(String startTime, String endTime, Integer areaId) {
        List<Map<String, Object>> centList = zuul.getCenterServiceIdList(areaId);
        if (CollectionUtils.isEmpty(centList)) {
            log.error("查询无结果");
            return JsonResult.success(Arrays.asList());
        }

        for (Map<String, Object> dept : centList) {
            Integer deptId = MapUtils.getInteger(dept, "id");
            //查询人员信息数量
            dept.put("peopleCount", zuul.getPeopleCountByDeptId(deptId, startTime, endTime));
            //查询新增房源套
            dept.put("housingCount", mapper.selectHousing(deptId, startTime, endTime));
            //查询新增房源间数
            dept.put("housingInfoCount", mapper.selectHousingInfoCount(deptId, startTime, endTime, null));
            //查询再跟客户
            List<Integer> userIds = mapper.selectAllWorderUserIds(startTime, endTime);
            List<Integer> uids = FilterCenterUtil.filterCenterUserId(userIds, Arrays.asList(deptId));
            dept.put("tailCount", mapper.selectWorderCount(uids, startTime, endTime));
            //查询本月成交
            dept.put("FixtureCount", mapper.selectFixtureNumber(deptId, startTime, endTime));
            //查询本月新收
            dept.put("NewOwnerCount", mapper.selectNewOwnerPactCount(deptId, startTime, endTime));
            //查询再租房源所有状态
            dept.put("AllHousingStateCount", mapper.selectHousingInfoCount(deptId, startTime, endTime, -1));
            //查询空房源
            dept.put("HousingEmptyCount", mapper.selectHousingInfoCount(deptId, startTime, endTime, 0));
            //查询中心平均租金
            dept.put("AvgMoney", mapper.selectAvgMoney(deptId, startTime, endTime));
            //查询可销售房源
            dept.put("marketCount", mapper.selectHousingInfoCount(deptId, startTime, endTime, -2));
            //查询可上架房源
            dept.put("putawayCount", mapper.selectHousingInfoCount(deptId, startTime, endTime, 1));
        }
        return JsonResult.success(centList);
    }


    ///////////////////////////////////////////////////////////////////////////
    // 子列表详情
    ///////////////////////////////////////////////////////////////////////////

    /**
     * 查询在职人员列的子表格
     *
     * @param page      分页
     * @param miId      服务中心编号
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return
     */
    public JsonResult getSubTableForPeople(Page page, String miId, String startTime, String endTime) {
        return JsonResult.success(zuul.selectPeopleData(page.getSize(), page.getCurrent(), miId, startTime, endTime));
    }

    /**
     * 查询新增房源 套 子表格数据
     *
     * @param page
     * @param miId      服务中心编号
     * @param startTime
     * @param endTime
     * @return
     */
    public JsonResult getSubTableForHousing(Page page, Integer miId, String startTime, String endTime) {
        IPage<Map<String, Object>> table = mapper.selectHousingForSubTable(page, miId, startTime, endTime);
        for (Map<String, Object> map : table.getRecords()) {
            String uid = MapUtils.getString(map, "HouseId");
            //收房专员名称查询
            JsonResult<List<Map<String, Object>>> result = zuul.getUserInfo(Arrays.asList(uid));
            String uName = "";
            if (result.isSuccess() && CollectionUtils.isNotEmpty(result.getResult())) {
                uName = (String) result.getResult().get(0).get("username");
            }
            map.put("InUserName", uName);
        }
        return JsonResult.success(table);
    }

    /**
     * 查询房间 间
     *
     * @param page
     * @param miId
     * @param startTime
     * @param endTime
     * @param type      1:新增房源 间
     *                  2:再租房源 所有状态
     *                  3:空置房源
     *                  4:可销售房源
     *                  5:上架中房源
     * @return
     */
    public JsonResult getSubTableForHouinfos(Page page, Integer miId, String startTime, String endTime, Integer type) {
        Integer state = null;
        switch (type) {
            case 1:
                //间
                state = null;
                break;
            case 2:
                //再租房源 所有状态
                state = -1;
                break;
            case 3:
                //空置房源
                state = 0;
                break;
            case 4:
                //可销售房源
                state = -2;
                break;
            case 5:
                //上架中房源
                state = 1;
                break;
        }
        IPage<Map<String, Object>> table = mapper.selectHousingInfoForSubTable(page, miId, startTime, endTime, state);
        for (Map<String, Object> map : table.getRecords()) {
            String uid = MapUtils.getString(map, "ShelfId");
            String uName = "";
            JsonResult<List<Map<String, Object>>> result = zuul.getUserInfo(Arrays.asList(uid));
            if (result.isSuccess() && CollectionUtils.isNotEmpty(result.getResult())) {
                uName = (String) result.getResult().get(0).get("username");
            }
            map.put("InUserName", uName);
            DateUtils.formatDateByMap(map);
        }
        return JsonResult.success(table);
    }

    /**
     * 查询再跟客户
     *
     * @param page
     * @param miId
     * @param startTime
     * @param endTime
     * @return
     */
    @SuppressWarnings("all")
    public JsonResult getSubTableForWorld(Page page, Integer miId, String startTime, String endTime) {
        List<Integer> userIds = mapper.selectAllWorderUserIds(startTime, endTime);
        List<Integer> uids = FilterCenterUtil.filterCenterUserId(userIds, Arrays.asList(miId));
        IPage<Map<String, Object>> table = mapper.selectWorderDataForSubTable(page, uids, startTime, endTime);
        for (Map<String, Object> map : table.getRecords()) {
            //接单人
            String operId = MapUtils.getString(map, "OperId");
            String uName = "";
            JsonResult<List<Map<String, Object>>> result = zuul.getUserInfo(Arrays.asList(operId));
            if (result.isSuccess() && CollectionUtils.isNotEmpty(result.getResult())) {
                uName = (String) result.getResult().get(0).get("username");
            }
            map.put("OperUserName", uName);

            //查询租客姓名
            String tenId = MapUtils.getString(map, "TenId");
            JsonResult<JSONObject> tenResult = tenantFeign.getWxInfoByTenId(tenId);
            String tenName = "";
            if (tenResult.isSuccess()) {
                JSONObject object = tenResult.getResult();
                tenName = object.getString("realName");
                if (StringUtils.isBlank(tenName)) {
                    tenName = object.getString("tenName");
                }
            }
            map.put("TenName", tenName);
        }
        return JsonResult.success(table);
    }

    /**
     * 查询成交数 表格数据
     *
     * @param page
     * @param miId
     * @param startTime
     * @param endTime
     * @return
     */
    @SuppressWarnings("all")
    public JsonResult getSubTableForFixture(Page page, Integer miId, String startTime, String endTime) {
        IPage<Map<String, Object>> table = mapper.selectFixtureForSubTable(page, miId, startTime, endTime);
        for (Map<String, Object> map : table.getRecords()) {
            //查询租客姓名
            String tenId = MapUtils.getString(map, "TenId");
            JsonResult<JSONObject> tenResult = tenantFeign.getWxInfoByTenId(tenId);
            String tenName = "";
            if (tenResult.isSuccess()) {
                JSONObject object = tenResult.getResult();
                tenName = object.getString("realName");
                if (StringUtils.isBlank(tenName)) {
                    tenName = object.getString("tenName");
                }
            }
            map.put("TenName", tenName);
            DateUtils.formatDateByMap(map);
        }
        return JsonResult.success(table);
    }


    /**
     * 查询新收 表格数据
     *
     * @param page
     * @param miId
     * @param startTime
     * @param endTime
     * @return
     */
    public JsonResult getSubTableForNewOwnerPact(Page page, Integer miId, String startTime, String endTime) {
        IPage<Map<String, Object>> table = mapper.selectNewOwnerPactForSubTable(page, miId, startTime, endTime);
        for (Map<String, Object> map : table.getRecords()) {
            DateUtils.formatDateByMap(map);
        }
        return JsonResult.success(table);
    }

    /**
     * 查询中心平均月租金
     *
     * @param page
     * @param miId
     * @param startTime
     * @param endTime
     * @return
     */
    public JsonResult getSubTableForAvg(Page page, Integer miId, String startTime, String endTime) {
        IPage<Map<String, Object>> table = mapper.selectAvgMoneyForSubTable(page, miId, startTime, endTime);
        return JsonResult.success(table);
    }
}
